package tau.dimes.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import tau.dimes.config.db.*;

public class Database
{
	private final Driver driver;
	private final Server server;
	private boolean initialized;
	String url = null;

	Database(Driver driver, Server server)
	{
		this.driver = driver;
		this.server = server;
	}

	public Driver getDriver()
	{
		return this.driver;
	}

	public Server getServer()
	{
		return this.server;
	}

	public ResultSet executeQuery(String query) throws DatabaseException
	{
		Statement statement = getStatement();
		try
		{
			return statement.executeQuery(query);
		}
		catch (SQLException e)
		{
			throw new DatabaseException(e);
		}
	}

	private Connection getConnection() throws DatabaseException
	{
		try
		{
			if (!initialized)
			{
				Class.forName(driver.getType());
				url = server.formatConnectionString(driver.getConnectionString());
				initialized = true;
			}

			return DriverManager.getConnection(url, server.getUser(), server.getPassword());
		}
		catch (Exception e)
		{
			throw new DatabaseException(e);
		}
	}

	public Statement getStatement() throws DatabaseException
	{
		try
		{
			return getConnection().createStatement();
		}
		catch (SQLException e)
		{
			throw new DatabaseException(e);
		}
	}

	public PreparedStatement getPreparedStatement(String sql) throws DatabaseException
	{
		try
		{
			return getConnection().prepareStatement(sql);
		}
		catch (SQLException e)
		{
			throw new DatabaseException(e);
		}
	}
}
